package com.itheima.health.service.impl;

import com.itheima.health.dao.MemberDao;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.dao.SetMealDao;
import com.itheima.health.dto.SetmealDto;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.ReportService;
import com.itheima.health.vo.ReportVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * 运营数据统计业务层实现类
 *
 * @author Administrator
 * @date 2023/4/27
 */
@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private SetMealDao setMealDao;

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private HttpServletResponse response;

    /**
     * 查询运营数据
     *
     * @return
     */
    @Override
    public ReportVo findAll() {

        // 当前今天日期
        LocalDate date = LocalDate.now();
        // 获取今天周几
        int weekDays = date.getDayOfWeek().getValue();
        // 本周第一天日期
        LocalDate weekDate = date.minusDays(weekDays - 1);
        // 本月第一天日期
        LocalDate monthDate = date.withDayOfMonth(1);

        // 今日到诊人数
        Integer todayVisitsNumber = orderDao.selectVisitsNumByDay(date, Order.ORDERSTATUS_YES);

        // 今日新会员数
        Integer todayNewMember = memberDao.selectNewMemberNumByDay(date);

        // 本周到诊人数
        Integer thisWeekVisitsNumber = orderDao.selectVisitsNumByWeek(weekDate, date, Order.ORDERSTATUS_YES);

        // 热门套餐
        List<SetmealDto> hotSetmeal = setMealDao.selectSetmealWithOrder();

        // 本月新会员数
        Integer thisMonthNewMember = memberDao.selectNewMemberByMonth(monthDate, date);

        // 本周新会员数
        Integer thisWeekNewMember = memberDao.selectNewMemberByWeek(weekDate, date);

        // 会员总数
        Integer totalMember = memberDao.selectNums();

        // 本月预约人数
        Integer thisMonthOrderNumber = orderDao.selectOrderNumByMonth(monthDate, date);

        // 今日预约人数
        Integer todayOrderNumber = orderDao.selectOrderNumByDay(date);

        // 本月到诊人数
        Integer thisMonthVisitsNumber = orderDao.selectVisitsNumByMonth(monthDate, date, Order.ORDERSTATUS_YES);

        // 本周预约人数
        Integer thisWeekOrderNumber = orderDao.selectOrderNumByWeek(weekDate, date);

        ReportVo reportVo = new ReportVo();
        reportVo.setTodayVisitsNumber(todayVisitsNumber);
        reportVo.setReportDate(date);
        reportVo.setTodayNewMember(todayNewMember);
        reportVo.setThisWeekVisitsNumber(thisWeekVisitsNumber);
        reportVo.setHotSetmeal(hotSetmeal);
        reportVo.setThisMonthNewMember(thisMonthNewMember);
        reportVo.setThisWeekNewMember(thisWeekNewMember);
        reportVo.setTotalMember(totalMember);
        reportVo.setThisMonthOrderNumber(thisMonthOrderNumber);
        reportVo.setThisMonthVisitsNumber(thisMonthVisitsNumber);
        reportVo.setTodayOrderNumber(todayOrderNumber);
        reportVo.setThisWeekOrderNumber(thisWeekOrderNumber);

        return reportVo;
    }

    /**
     * 导出excel表格
     *
     * @return
     */
//    @Override
//    public void export() throws IOException {
//
//        ReportVo reportVo = findAll();
//
//        // 在内存中创建一个Excel文件
//        XSSFWorkbook workbook = new XSSFWorkbook();
//        // 创建工作表，指定工作表名称
//        XSSFSheet sheet = workbook.createSheet("运营数据统计");
//
//        // 设置单元格居中
//        XSSFCellStyle cellStyle = workbook.createCellStyle();
//        cellStyle.setAlignment(HorizontalAlignment.CENTER);
//
//        // 创建行，0表示第一行
//        XSSFRow row = sheet.createRow(0);
//        XSSFCell rowCell = row.createCell(0);
//        rowCell.setCellStyle(cellStyle);
//        rowCell.setCellValue("运营数据统计");
//        CellRangeAddress address = new CellRangeAddress(0, 0, 0, 4);
//        sheet.addMergedRegion(address);
//
//        // 创建单元格，1表示第一个单元格
//        XSSFRow row1 = sheet.createRow(1);
//        row1.createCell(0).setCellValue("新增会员数");
//        row1.createCell(1).setCellValue(reportVo.getTodayNewMember());
//        row1.createCell(2).setCellValue("总会员数");
//        row1.createCell(3).setCellValue(reportVo.getTotalMember());
//
//        XSSFRow row2 = sheet.createRow(2);
//        row2.createCell(0).setCellValue("本周新增会员数");
//        row2.createCell(1).setCellValue(reportVo.getThisWeekNewMember());
//        row2.createCell(2).setCellValue("本月新增会员数");
//        row2.createCell(3).setCellValue(reportVo.getThisMonthNewMember());
//
//
//        XSSFRow row3 = sheet.createRow(3);
//        XSSFCell rowCell3 = row3.createCell(0);
//        rowCell3.setCellStyle(cellStyle);
//        rowCell3.setCellValue("预约到诊数据统计");
//        sheet.addMergedRegion(new CellRangeAddress(3, 3, 0, 4));
//
//        XSSFRow row4 = sheet.createRow(4);
//        row4.createCell(0).setCellValue("今日预约数");
//        row4.createCell(1).setCellValue(reportVo.getTodayOrderNumber());
//        row4.createCell(2).setCellValue("今日到诊数");
//        row4.createCell(3).setCellValue(reportVo.getTodayVisitsNumber());
//
//        XSSFRow row5 = sheet.createRow(5);
//        row5.createCell(0).setCellValue("本周预约数");
//        row5.createCell(1).setCellValue(reportVo.getThisWeekOrderNumber());
//        row5.createCell(2).setCellValue("本周到诊数");
//        row5.createCell(3).setCellValue(reportVo.getThisWeekVisitsNumber());
//
//        XSSFRow row6 = sheet.createRow(6);
//        row6.createCell(0).setCellValue("本月预约数");
//        row6.createCell(1).setCellValue(reportVo.getThisMonthOrderNumber());
//        row6.createCell(2).setCellValue("本月到诊数");
//        row6.createCell(3).setCellValue(reportVo.getThisMonthVisitsNumber());
//
//        XSSFRow row7 = sheet.createRow(7);
//        XSSFCell rowCell7 = row7.createCell(0);
//        rowCell7.setCellStyle(cellStyle);
//        rowCell7.setCellValue("热门套餐");
//        sheet.addMergedRegion(new CellRangeAddress(7, 7, 0, 4));
//
//        XSSFRow row8 = sheet.createRow(8);
//        row8.createCell(0).setCellValue("套餐名称");
//        row8.createCell(1).setCellValue("预约数量");
//        row8.createCell(2).setCellValue("占比");
//        row8.createCell(3).setCellValue("备注");
//
//        reportVo.getHotSetmeal().forEach(setMeal -> {
//            XSSFRow row9 = sheet.createRow(9);
//            row9.createCell(0).setCellValue(setMeal.getName());
//            row9.createCell(1).setCellValue(setMeal.getSetmealCount());
//            row9.createCell(2).setCellValue(setMeal.getProportion());
//            row9.createCell(3).setCellValue("");
//        });
//        List<SetmealDto> setmealDtoList = reportVo.getHotSetmeal();
//        for (int i = 0; i < setmealDtoList.size(); i++) {
//            XSSFRow row9 = sheet.createRow(9 + i);
//            row9.createCell(0).setCellValue(setmealDtoList.get(i).getName());
//            row9.createCell(1).setCellValue(setmealDtoList.get(i).getSetmealCount());
//            row9.createCell(2).setCellValue(setmealDtoList.get(i).getProportion());
//            row9.createCell(3).setCellValue("");
//        }
//
//
//        String fileName = "D:\\会员数据统计.xlsx";
//
//        //通过输出流将workbook对象输出到磁盘
//        FileOutputStream out = new FileOutputStream(fileName);
//        workbook.write(out);
//        out.flush();//清空缓冲区
//        out.close();
//        workbook.close();
//
//    }

    /**
     * 导出excel表格
     *
     * @throws IOException
     */
    @Override
    public Result export() throws IOException {

        log.info("【导出运营数据报表】开始");
        // 1. RPC-获取数据
        ReportVo reportVo = findAll();

        // 2. 读取模板构造workBook
        try (InputStream is = this.getClass().getClassLoader().getResourceAsStream("report_template.xlsx");
             Workbook workbook = new XSSFWorkbook(is);
             OutputStream os = response.getOutputStream()) {
            Sheet sheet = workbook.getSheetAt(0);

            // 3. 填入数据
            // 日期
            sheet.getRow(2).getCell(5).setCellValue(String.valueOf(reportVo.getReportDate()));

            //会员统计数据
            sheet.getRow(4).getCell(5).setCellValue(reportVo.getTodayNewMember());
            sheet.getRow(4).getCell(7).setCellValue(reportVo.getTotalMember());
            sheet.getRow(5).getCell(5).setCellValue(reportVo.getThisWeekNewMember());
            sheet.getRow(5).getCell(7).setCellValue(reportVo.getThisMonthNewMember());
            //预约到诊数据统计
            sheet.getRow(7).getCell(5).setCellValue(reportVo.getTodayOrderNumber());
            sheet.getRow(7).getCell(7).setCellValue(reportVo.getTodayVisitsNumber());
            sheet.getRow(8).getCell(5).setCellValue(reportVo.getThisWeekOrderNumber());
            sheet.getRow(8).getCell(7).setCellValue(reportVo.getThisWeekVisitsNumber());
            sheet.getRow(9).getCell(5).setCellValue(reportVo.getThisMonthOrderNumber());
            sheet.getRow(9).getCell(7).setCellValue(reportVo.getThisMonthVisitsNumber());
            //热门套餐
            int rowNum = 12;
            for (SetmealDto setMeal : reportVo.getHotSetmeal()) {
                Row row = sheet.getRow(rowNum);
                row.getCell(4).setCellValue(setMeal.getName());
                row.getCell(5).setCellValue(setMeal.getSetmealCount());
                row.getCell(6).setCellValue(setMeal.getProportion());
                rowNum++;
            }

            // 4. 写入网络输出流
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;fileName=" + reportVo.getReportDate() + "_report.xlsx");
            workbook.write(os);
        } catch (IOException ex) {
            log.error("出现异常：{}", ex.getMessage());
        }
        return null;
    }


}
